package org.example.greenhouse.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class ImageUtils {

    public static String getImageStrFromUrl(String imgURL) {
        byte[] data = null;
        try {
            URL url = new URL(imgURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000); // 设置连接超时
            conn.setReadTimeout(10 * 1000);  // 设置读取超时

            // 检查响应码
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inStream = conn.getInputStream();
                data = readAllBytes(inStream); // 读取所有字节
                inStream.close();
            } else {
                throw new RuntimeException("请求失败，状态码：" + conn.getResponseCode());
            }
        } catch (IOException e) {
            throw new RuntimeException("图片下载失败: " + e.getMessage());
        }

        // 将图片字节数组转换为 Base64 编码
        if (data != null) {
            return Base64.getEncoder().encodeToString(data);
        } else {
            throw new RuntimeException("图片数据为空");
        }
    }

    private static byte[] readAllBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
        return output.toByteArray();
    }
}